//
//  Glob.m
//  Calendar
//
//  Created by glave on 13-11-26.
//
//

#import "Glob.h"
#import <CoreText/CoreText.h>
#import "UserEntity.h"
#import "RDVTabBarController.h"
//#import "const.h"
#define ARRSIZE(a)      (sizeof(a) / sizeof(a[0]))


#define kCustomButtonHeight		29.0

// 每次只保存N个浏览记录
#define kSaveViewedTopicsCountMax 50
#define kSaveViewedTopicsFileName @"viewed_topics"

static NSString *companyUrl = @"";

@implementation Glob

static id userInfo = nil;
static id topicInfo = nil;
static id postInfo = nil;
static BOOL isWWAN = YES;
static BOOL hasNetwork = NO;

@synthesize reachability;

+(UIBarButtonItem *)getNavigationBarBackButton:(UIViewController *)target imgName:(NSString *)name
{
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 31, 31)];
    
    [backBtn setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    
    [backBtn addTarget:target action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
	UIBarButtonItem *naviItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    
    return naviItem;
}

+(UIBarButtonItem *)getNavigationBarSetButton:(UIViewController *)target imgName:(NSString *)name
{
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 31, 31)];
    
    [backBtn setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    
    [backBtn addTarget:target action:@selector(tapItem:) forControlEvents:UIControlEventTouchUpInside];
    
	UIBarButtonItem *naviItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    
    return naviItem;
}

+ (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    
    return destDate;
    
}

+ (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息 +0000。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
        
    return destDateString;
    
}


+(CGMutablePathRef)pathwithFrame:(CGRect)frame withRadius:(float)radius
{
    CGPoint x1,x2,x3,x4; //x为4个顶点
    CGPoint y1,y2,y3,y4,y5,y6,y7,y8; //y为4个控制点
    //从左上角顶点开始，顺时针旋转,x1->y1->y2->x2
    
    x1 = frame.origin;
    x2 = CGPointMake(frame.origin.x+frame.size.width, frame.origin.y);
    x3 = CGPointMake(frame.origin.x+frame.size.width, frame.origin.y+frame.size.height);
    x4 = CGPointMake(frame.origin.x                 , frame.origin.y+frame.size.height);
    
    
    y1 = CGPointMake(frame.origin.x+radius, frame.origin.y);
    y2 = CGPointMake(frame.origin.x+frame.size.width-radius, frame.origin.y);
    y3 = CGPointMake(frame.origin.x+frame.size.width, frame.origin.y+radius);
    y4 = CGPointMake(frame.origin.x+frame.size.width, frame.origin.y+frame.size.height-radius);
    
    y5 = CGPointMake(frame.origin.x+frame.size.width-radius, frame.origin.y+frame.size.height);
    y6 = CGPointMake(frame.origin.x+radius, frame.origin.y+frame.size.height);
    y7 = CGPointMake(frame.origin.x, frame.origin.y+frame.size.height-radius);
    y8 = CGPointMake(frame.origin.x, frame.origin.y+radius);
    
    
    CGMutablePathRef pathRef = CGPathCreateMutable();
    
    if (radius<=0) {
        CGPathMoveToPoint(pathRef,    &CGAffineTransformIdentity, x1.x,x1.y);
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, x2.x,x2.y);
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, x3.x,x3.y);
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, x4.x,x4.y);
    }else
    {
        CGPathMoveToPoint(pathRef,    &CGAffineTransformIdentity, y1.x,y1.y);
        
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, y2.x,y2.y);
        CGPathAddArcToPoint(pathRef, &CGAffineTransformIdentity,  x2.x,x2.y,y3.x,y3.y,radius);
        
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, y4.x,y4.y);
        CGPathAddArcToPoint(pathRef, &CGAffineTransformIdentity,  x3.x,x3.y,y5.x,y5.y,radius);
        
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, y6.x,y6.y);
        CGPathAddArcToPoint(pathRef, &CGAffineTransformIdentity,  x4.x,x4.y,y7.x,y7.y,radius);
        
        CGPathAddLineToPoint(pathRef, &CGAffineTransformIdentity, y8.x,y8.y);
        CGPathAddArcToPoint(pathRef, &CGAffineTransformIdentity,  x1.x,x1.y,y1.x,y1.y,radius);
        
    }
    
    
    CGPathCloseSubpath(pathRef);
    
    return pathRef;
}


+ (void) setCompanyUrl:(NSString*)urlString
{
    companyUrl = [NSString stringWithFormat:@"%@",urlString];
    [[NSUserDefaults standardUserDefaults] setObject:companyUrl forKey:@"companyUrl"];
}

+ (NSString*) getCompanyUrl
{
    if ([companyUrl isEqualToString:@""] || [companyUrl isEqualToString:@"http://"]) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"companyUrl"]) {
            companyUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"companyUrl"];
        }
    }
	return companyUrl;
}


+ (void) setUserInfo:(id)info
{
	if (info) {
		userInfo = info;
		[[NSUserDefaults standardUserDefaults] setValue:[(UserEntity*)userInfo name] forKey:@"login_name"];
	}
	else {
        userInfo = nil;
		[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"login_name"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (id) getUserInfo
{
	return userInfo;
}

+ (void) setPostInfo:(id)info
{
	postInfo = info;
}

+ (id) getPostInfo
{
	return postInfo;
}

+ (void) setTopicInfo:(id)info
{
	topicInfo = info ;
}

+ (id) getTopicInfo
{
	return topicInfo;
}

//自动登录验证
+ (void)loadLastUserAccount
{
//	NSString* name = [[NSUserDefaults standardUserDefaults] valueForKey:@"login_name"];
//	if (name.length > 0) {
//        
//		UserEntity* entity = [UserEntity findUserAccountByName:name];
//		if (![Glob getUserInfo] && entity) {
//			AccountC* account = [[AccountC alloc] init];
//            if (entity.password==nil) {
//                //                [Glob saveUserInfo:entity];
//                [account loginWithType];
//            }else [account loginWithName:entity.name password:entity.password];
//			[account release];
//		}
//	}
//	else {
//		[[AnalysisModel sharedModel] login:nil];
//	}
}

+ (void)clearLastUserAccount
{
    
    NSLog(@"clear last user account");
    if ([Glob getUserInfo]) {
		NSURL* url = [NSURL URLWithString:LOGIN_URL([Glob getCompanyUrl])];
		NSArray* cookies = [[NSArray alloc] initWithArray:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url]];
		for (NSHTTPCookie* cookie in cookies) {
			if ([cookie.name rangeOfString:@"winduser"].length > 0) {
				[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
                //				break;
			}
		}
//		[cookies release];
	}
//	[[AnalysisModel sharedModel] logoutImmediate];
}

+ (void) setShowAuthorByDefault:(BOOL)value
{
	[[NSUserDefaults standardUserDefaults] setBool:value forKey:@"show_author"];
}

+ (BOOL) isShowAuthorByDefault
{
	return [[NSUserDefaults standardUserDefaults] boolForKey:@"show_author"];
}

+ (void) setShowImageByDefault:(BOOL)value
{
	//
}

//+ (BOOL) isShowImageByDefault
//{
//	return !(isWWAN && ![Glob isNotShowImageByWWAN]);
//}
//
//+ (void) setNotShowImageByWWAN:(BOOL)value
//{
//    NSLog(@"909090");
//	[[NSUserDefaults standardUserDefaults] setBool:!value forKey:@"show_image_inwwan"];
//}
//
//+ (BOOL) isWWAN
//{
//	return isWWAN;
//}
//
//+ (BOOL) isNotShowImageByWWAN
//{
//    NSLog(@"gggg==%d",![[NSUserDefaults standardUserDefaults] boolForKey:@"show_image_inwwan"]);
//	return ![[NSUserDefaults standardUserDefaults] boolForKey:@"show_image_inwwan"];
//}


//+ (UIBarButtonItem*)getReload
//{
//	if (!userInfo) {
//		return [[[UIBarButtonItem alloc] initWithTitle:@"刷新"
//                                                 style:UIBarButtonItemStyleBordered
//                                                target:self
//                                                action:@selector(refreshBigTiaoView:)] autorelease];
//	}
//	else {
//		return nil;
//	}
//}


//- (id)init
//{
//	self = [super init];
//	if (self) {
//		[[NSNotificationCenter defaultCenter] addObserver:self
//												 selector:@selector(networkChanged:)
//													 name:kReachabilityChangedNotification
//												   object:nil];
//	}
//	return self;
//}

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[self.reachability stopNotifier];
	self.reachability = nil;
//	[super dealloc];
}

//- (void) spyNetwork
//{
//	if (!self.reachability) {
//		self.reachability = [Reachability reachabilityForInternetConnection];
//		isWWAN = [self.reachability isReachableViaWWAN];
//		hasNetwork = [self.reachability isReachable];
//		[self.reachability startNotifier];
//	}
//}


//
//- (void)networkChanged:(NSNotification*)noti
//{
//	Reachability* reac = (Reachability*)noti.object;
//	if ([reac isReachableViaWWAN]) {
//		isWWAN = YES;
//	}
//	else if ([reac isReachableViaWiFi]) {
//		isWWAN = NO;
//	}
//	hasNetwork = [reac isReachable];
//}
//+ (void) saveUserInfo:(id)userInfo{
//    UserEntity* entity = (UserEntity *)userInfo;
//    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
//                              entity.accessTokenKey, @"AccessTokenKey",
//                              entity.expirationDateKey, @"ExpirationDateKey",
//                              entity.userIDKey, @"UserIDKey",
//                              entity.type,@"Type",nil];
//    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"AuthLogin"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//}


+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
+ (UIDeviceResolution) currentResolution {
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)]) {
            CGSize result = [[UIScreen mainScreen] bounds].size;
            result = CGSizeMake(result.width * [UIScreen mainScreen].scale, result.height * [UIScreen mainScreen].scale);
            if (result.height <= 480.0f)
                return UIDevice_iPhoneStandardRes;
            return (result.height > 960 ? UIDevice_iPhoneTallerHiRes : UIDevice_iPhoneHiRes);
        } else
            return UIDevice_iPhoneStandardRes;
    } else
        return (([[UIScreen mainScreen] respondsToSelector: @selector(scale)]) ? UIDevice_iPadHiRes : UIDevice_iPadStandardRes);
}

//将yyyy-MM-dd HH:mm:ss格式时间转换成时间戳
+(long)changeTimeToTimeSp:(NSString *)timeStr{
    long time;
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate=[format dateFromString:timeStr];
    time= (long)[fromdate timeIntervalSince1970];
    return time;
}
//获取当前系统的时间戳
+(long)getTimeSp{
    long time;
    NSDate *fromdate=[NSDate date];
    time=(long)[fromdate timeIntervalSince1970];
    return time;
}

+(void)hideTabBar
{
    UIApplication* application = [UIApplication sharedApplication];
    AppDelegate* appdelegate = (AppDelegate*)application.delegate;
//    RDVTabBarController * tab = appdelegate.tabBarController;
//    [tab setTabBarHidden:YES];
}

+(void)showTabBar
{
    UIApplication* application = [UIApplication sharedApplication];
    AppDelegate* appdelegate = (AppDelegate*)application.delegate;
//    RDVTabBarController * tab = appdelegate.tabBarController;
//    [tab setTabBarHidden:NO];
}

static MBProgressHUD *HUD;
//MBProgressHUD 的使用方式，只对外两个方法，可以随时使用(但会有警告！)，其中窗口的 alpha 值 可以在源程序里修改。
+ (void)showHUD:(NSString *)msg{
    
    HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
    [[UIApplication sharedApplication].keyWindow addSubview:HUD];
    HUD.dimBackground = YES;
    HUD.labelText = msg;
    [HUD show:YES];
}
+ (void)removeHUD{
    
    [HUD hide:YES];
    [HUD removeFromSuperViewOnHide];
}
@end
